﻿using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;

class JoinRoomPanel : MonoBehaviour
{
    [SerializeField] TMP_InputField invitationCode;
    [SerializeField] TMP_InputField nameIF;
    [SerializeField] TMP_InputField pwdIF;
    [SerializeField] Button exitBT;
    [SerializeField] Button ensureBT;    

    private void OnEnable()
    {
        exitBT.onClick.AddListener(OnExitBTClick);
        ensureBT.onClick.AddListener(OnEnsureBTClick);
    }

    private void OnDisable()
    {
        exitBT.onClick.RemoveListener(OnExitBTClick);
        ensureBT.onClick.RemoveListener (OnEnsureBTClick);
    }
    
    void OnExitBTClick()
    {
        gameObject.SetActive(false);
        NetworkManager.Singleton.Shutdown();        
    }

    void OnEnsureBTClick()
    {
        string[] tokens=invitationCode.text.Split(':');
        if (tokens.Length == 2 && ushort.TryParse(tokens[1], out ushort port))
        {
            ConnectionManager.Instance.StartClient(tokens[0], port, nameIF.text, pwdIF.text);
        }
        else
            Debug.Log("邀请码格式错误");
    }

    private void OnConnectedToServer()
    {
        Debug.Log("connected OnConnectedToServer");
    }
}